package com.aaa.service.impl;

import com.aaa.entity.Menu;
import com.aaa.entity.Staff;
import com.aaa.mapper.MenuMapper;
import com.aaa.service.MenuService;
import com.aaa.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private HttpSession session;

    @Override
    public R getMenu() {
        Staff staff = (Staff) session.getAttribute("staff");//获取当前登录的信息.
        //根据用户获取对应的菜单
        List<Menu> menus = menuMapper.selectByRoleId(staff.getRoleid());
        //得到一级菜单
        List<Menu> first=new ArrayList<>();//存放一级菜单
        //遍历所有菜单
        for(Menu m:menus){
            if(m.getMpid()==0){//是一级菜单
                first.add(m);
            }
        }
        //查询一级菜单对应的二级菜单
        for(Menu f:first){
            //创建一个集合存放当前一级菜单的二级菜单
            List<Menu> children=new ArrayList<>();
            for(Menu m:menus){
                if(f.getMid().equals(m.getMpid())){
                    children.add(m);
                }
            }
            f.setChildren(children);
        }
        return new R(200,"获取左侧菜单成功",first);
    }

    @Override
    public R findByRoleId(Integer roleid) {
        //查询所有得菜单--层级关系
        List<Menu> menus = menuMapper.selectAll();
        //得到一级菜单
        List<Menu> first=new ArrayList<>();//存放一级菜单
        //遍历所有菜单
        for(Menu m:menus){
            if(m.getMpid()==0){//是一级菜单
                first.add(m);
            }
        }
        //查询一级菜单对应的二级菜单
        for(Menu f:first){
            //创建一个集合存放当前一级菜单的二级菜单
            List<Menu> children=new ArrayList<>();
            for(Menu m:menus){
                if(f.getMid().equals(m.getMpid())){
                    children.add(m);
                }
            }
            f.setChildren(children);
        }
        //查询当前角色对应的菜单id
        List<Integer> menuIds = menuMapper.selectMenuIdByRoleId(roleid);

        Map<String,Object> map=new HashMap<>();
        map.put("menus",first);
        map.put("menuIds",menuIds);
        return new R(200,"获取菜单成功",map);
    }

    @Override
    @Transactional //spring只要看到该注解 表示该方法有事务管理
    public R confirmFen(Integer roleid, Integer[] cids) {
        //1.删除该角色对应的原来的菜单id
        int row=menuMapper.deleteByRoleid(roleid);
        //2.添加该角色对应的新的菜单id
        menuMapper.batchInsert(roleid,cids);
        return new R(200,"分配菜单成功",null);
    }

}

/**
 * 1.
 */











